<script lang="ts">
import { defineComponent, ref, computed } from 'vue'
import TableTitle from './components/TableTitle.vue'
import TableSetting from './components/settings/index.vue'
import { useTableList } from './hooks/useTableList'
import { BasicTableColumn } from './typing'
import { cloneDeep } from 'lodash-es'

export default defineComponent({
  name: 'TableList',
  components: { TableTitle, TableSetting },
  props: {
    title: { type: String },
    basicColumns: { type: Array<BasicTableColumn>, default: () => [] },
    indexChecked: { type: Boolean, default: false },
    selectChecked: { type: Boolean, default: false },
    showSetting: { type: Boolean, default: true },
    showActions: { type: Boolean, default: false }
  },
  setup(props) {
    const columnsCheckedState = ref({
      indexChecked: props.indexChecked,
      selectChecked: props.selectChecked
    })
    const sortColumns = ref<BasicTableColumn[]>(cloneDeep(props.basicColumns))

    const { indexColumn, actionsColumn } = useTableList()

    const columns = computed(() => {
      let showColumns = sortColumns.value.filter(
        (item: BasicTableColumn) => item.checked
      )
      const indexColumnData = columnsCheckedState.value.indexChecked
        ? [indexColumn]
        : []
      return props.showActions
        ? [...indexColumnData, ...showColumns, actionsColumn]
        : [...indexColumnData, ...showColumns]
    })
    const onResetColumns = () => {
      sortColumns.value = props.basicColumns.map(item => {
        item.checked = true
        item.fixed = false
        return item
      })
    }
    return {
      columnsCheckedState,
      sortColumns,
      columns,
      onResetColumns
    }
  }
})
</script>

<template>
  <a-space
    class="system-tablelist-wrapper"
    direction="vertical"
    size="middle"
    style="width: 100%"
  >
    <a-row justify="space-between" class="table-header-wrapper">
      <a-col>
        <TableTitle :title="title">
          <slot name="title"></slot>
        </TableTitle>
      </a-col>
      <a-col class="system-table-header-operate">
        <slot name="toolbar"></slot>
        <a-divider type="vertical" v-if="$slots.toolbar && showSetting" />
        <TableSetting
          v-if="showSetting"
          :sortColumns="sortColumns"
          :columnsCheckedState="columnsCheckedState"
          @refresh="$emit('refresh')"
          @reset="$emit('reset')"
        />
      </a-col>
    </a-row>
    <slot
      name="tableContent"
      v-bind="{ columns, selectChecked: columnsCheckedState.selectChecked }"
    ></slot>
  </a-space>
</template>